<!-- src/views/Home.vue -->
<template>
  <div class="home-page">
    <UserProfile class="floating-profile" @import-plan="handleImportPlan" />
    <el-container class="common-layout">
      <SideBar ref="sidebarRef" :map-ref="mapRef" :map-loaded="mapLoaded" @add-marker="handleAddMarker"
        @remove-marker="handleRemoveMarker" @show-analysis="handleShowAnalysis"
        @spots-recommended="handleSpotsRecommended" />
      <el-main class="map-container">
        <map-view ref="mapRef" @map-loaded="handleMapLoaded" />
      </el-main>
    </el-container>
    <!-- 右侧 AI 抽屉 -->
    <AIDrawer ref="aiDrawerRef" v-model:mode="chat" @spot-search="handleSpotSearch" />

    <!-- 右下角按钮组 -->
    <div class="bottom-actions">
      <el-button class="travel-btn" @click="handleWuhanTravel">
        <img src="@/assets/yinghua.png" class="travel-icon" />
        文旅武汉
      </el-button>
      <el-button @click="showHotspotModal">网红打卡地</el-button>
      <el-button @click="handleReset">重置规划</el-button>
      <el-button type="primary" @click="handleSave">保存规划</el-button>
    </div>
  </div>
  <SavePlanDialog ref="savePlanRef" @confirm="handleSaveConfirm" />
  <HotspotModal v-model:visible="hotspotModalVisible" />
</template>


<script setup>
import UserProfile from '../components/user/UserProfile.vue'
import SideBar from '../components/sidebar/SideBar.vue'
import MapView from '../components/map/MapView.vue'
import AIDrawer from '../components/ai/AIResult/AIDrawer.vue'
import SavePlanDialog from '@/components/user/SavePlanDialog.vue'
import { ElMessage } from 'element-plus'
import { ref, onMounted, onUnmounted } from 'vue'
import HotspotModal from '@/components/hotspot/HotspotModal.vue'

const mapRef = ref(null)
const aiDrawerRef = ref(null)
const sidebarRef = ref(null)
const savePlanRef = ref()
const mapLoaded = ref(false)

const handleAddMarker = (spot) => {
  mapRef.value?.addMarker(spot)
}

const handleShowAnalysis = (analysis) => {
  console.log('接收到分析数据:', analysis)
  aiDrawerRef.value?.showAnalysis(analysis)
}

const handleWuhanTravel = () => {
  window.open('https://wlj.wuhan.gov.cn/', '_blank')
}


const hotspotModalVisible = ref(false)
const showHotspotModal = () => {
  hotspotModalVisible.value = true
}

const handleSpotsRecommended = (spots) => {
  console.log('接收到推荐景点:', spots)
  aiDrawerRef.value?.showSpots(spots)
}
const handleRemoveMarker = (attractionId) => {
  mapRef.value?.removeMarker(attractionId)
}

const handleSave = () => {
  if (!savePlanRef.value) {
    ElMessage.error('系统错误')
    return
  }
  savePlanRef.value.dialogVisible = true
}

const handleReset = () => {
  // 清空预填表单
  savePlanRef.value?.prefillForm({
    planName: '',
    status: 'draft',
    numPeople: 1,
    avgAge: 25,
    budget: 0
  })

  // 清空规划列表组件
  const draggableList = sidebarRef.value?.planningDrawerRef?.draggableListRef
  if (draggableList) {
    draggableList.importedPlanId = null  // 清除导入ID
  }
  const planningDrawer = sidebarRef.value?.planningDrawerRef
  if (planningDrawer) {
    planningDrawer.clearSpots()
  }
  sidebarRef.value?.planningDrawerRef.clearSpots()

  if (sidebarRef.value.planningDrawerRef.isOpen) {
    sidebarRef.value.planningDrawerRef.togglePlanningDrawer()
  }

  ElMessage.success('已重置所有内容')
}

const handleSpotSearch = (spotName) => {
  console.log('搜索景点:', spotName)
  // 调用 sidebar 的搜索方法
  sidebarRef.value?.searchSpot(spotName)
}
const handleSaveConfirm = (formData) => {
  if (!sidebarRef.value) {
    ElMessage.error('无法获取侧边栏组件')
    return
  }
  // 直接获取 planningDrawerRef,不需要再加 .value
  const planningDrawer = sidebarRef.value.planningDrawerRef
  if (!planningDrawer) {  // 移除 .value
    ElMessage.error('无法获取规划抽屉组件')
    return
  }
  // 访问 draggableListRef 组件
  const draggableList = planningDrawer.draggableListRef
  if (!draggableList) {
    ElMessage.error('无法获取规划列表组件')
    return
  }
  // 调用保存方法
  draggableList.handleSavePlan(formData)
}

const handleImportPlan = ({ planId, planInfo }) => {
  if (!sidebarRef.value?.planningDrawerRef?.draggableListRef) {
    ElMessage.error('系统错误')
    return
  }
  // 先预填表单
  savePlanRef.value?.prefillForm(planInfo)
  // 确保规划栏打开
  if (!sidebarRef.value.planningDrawerRef.isOpen) {
    sidebarRef.value.planningDrawerRef.togglePlanningDrawer()
  }
  // 再导入规划内容
  sidebarRef.value.planningDrawerRef.draggableListRef.importPlan(planId)
}
const handleMapLoaded = async () => {
  mapLoaded.value = true
  // 等待定位完成
  await new Promise(resolve => setTimeout(resolve, 1000))
  // 加载默认景点
  sidebarRef.value?.loadDefaultSpots()
}

// 添加新的定位就绪处理函数
onMounted(() => {
  window.addEventListener('location-ready', () => {
    sidebarRef.value?.loadDefaultSpots()
  })
})

onUnmounted(() => {
  window.removeEventListener('location-ready', () => {
    sidebarRef.value?.loadDefaultSpots()
  })
})
</script>

<style scoped>
.home-page {
  height: 100vh;
  position: relative;
}

.map-container {
  padding: 0;
  height: 100%;
  z-index: 1;
  /* 添加这行，确保地图在最底层 */
}

.floating-profile {
  position: fixed;
  top: 20px;
  right: 20px;
  z-index: 1000;
}

.common-layout {
  height: 100vh;
}

.map-container {
  padding: 0;
  height: 100%;
}

.bottom-actions {
  position: fixed;
  right: 60px;
  bottom: 13px;
  z-index: 188;
  /* 在地图上方，在抽屉下方 */
  display: flex;
  gap: 10px;
}

.travel-icon {
  width: 16px;
  height: 16px;
  margin-right: 4px;
  vertical-align: middle;
}

</style>